package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"sort"
)

type SysApp struct {
	Id          int    `orm:"column(id);auto"`
	Title       string `orm:"column(title);size(16)" description:"站名"`
	MainId      int    `orm:"column(main_id)" description:"主号ID"`
	AppType     int8   `orm:"column(app_type)" description:"应用类型"`
	AppName     string `orm:"column(app_name);size(16)" description:"应用名称"`
	AppShort    string `orm:"column(app_short);size(8)" description:"应用短名"`
	BindHost    string `orm:"column(bind_host);size(50)" description:"绑定的域名"`
	SmsId       string `orm:"column(sms_id);size(6);null" description:"短信模板ID"`
	DevOriginal string `orm:"column(dev_original);size(32);null" description:"原始ID"`
	DevId       string `orm:"column(dev_id);size(32);null" description:"应用ID"`
	DevSecret   string `orm:"column(dev_secret);size(64);null" description:"应用秘钥"`
	DevToken    string `orm:"column(dev_token);size(32);null" description:"应用令牌"`
	DevMsgKey   string `orm:"column(dev_msg_key);size(64);null" description:"消息加解密密钥"`
	PayMchid    string `orm:"column(pay_mchid);size(32);null" description:"支付商户号"`
	PaySecret   string `orm:"column(pay_secret);size(64);null" description:"支付秘钥"`
	ServiceTime string `orm:"column(service_time);size(30);null" description:"客服时间"`
	ServiceTel  string `orm:"column(service_tel);size(20);null" description:"客服电话"`
	ServiceQq   string `orm:"column(service_qq);size(20);null" description:"客服QQ"`
	ServiceImg  string `orm:"column(service_img);size(255);null" description:"公众号二维码"`
	PlatShort   string `orm:"column(plat_short);size(8)" description:"渠道短名"`
	PlatName    string `orm:"column(plat_name);size(30)" description:"渠道名称"`
	IsLinkage   int8   `orm:"column(is_linkage)" description:"是否联动"`
	IsDelete    int8   `orm:"column(is_delete)" description:"是否删除"`
}

func (t *SysApp) TableName() string {
	return "sys_app"
}

func init() {
	orm.RegisterModel(new(SysApp))
}

// GetAllSysApp retrieves all SysApp matches certain condition. Returns empty list if
// no records exist
func GetAllSysApp() ([]*SysApp, error) {
	sysApps := make([]*SysApp, 0)
	_, err := orm.NewOrm().QueryTable("sys_app").All(&sysApps)
	//_, err := o.Raw("SELECT * from sys_app").QueryRows(&sysApps)
	if err != nil {
		fmt.Println("select sys_app error", err)
		return nil, err
	}
	return sysApps, nil
}

func GetLinkageApp() []*SysApp {
	appId := make([]int, 0)
	for id, _ := range appHash {
		appId = append(appId, id)
	}
	sort.Ints(appId)

	appList := make([]*SysApp, 0)
	for _, id := range appId {
		if appHash[id].IsLinkage == 1 {
			appList = append(appList, appHash[id])
		}
	}
	return appList
}
